package com.sxc.download;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("文件下载开始....");

        // 1. 设置请求的编码
        req.setCharacterEncoding("UTF-8");
        // 2. 获取参数
        String fileName = req.getParameter("fileName");
        // 3. 参数的非空判断
        if(fileName == null || "".equals(fileName.trim())) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("请输入要下载的文件名");
            resp.getWriter().close();
            return;
        }

        // 得到图片存放的路径
        String path = req.getServletContext().getRealPath("/download/");
        // 通过路径得到file对象
        File file = new File(path + fileName);
        // 判断文件对象是否存在
        if(file.exists() && file.isFile()) {
            // 设置相应类型(浏览器无法处理或激活某个程序来处理的MIME类型)
            resp.setContentType("application/x-msdownload");
            // 设置响应头
            resp.setHeader("content-Disposition", "attachment;filename" + fileName);
            // 得到file文件输入流
            InputStream is = new FileInputStream(file);
            // 得到字节输出流
            ServletOutputStream os = resp.getOutputStream();
            // 定义字节数组
            byte[] bytes = new byte[1024];
            //定义长度
            int len = 0;
            // 循环输出
            while((len = is.read(bytes)) != -1) {
                // 输出
                os.write(bytes, 0, len);
            }
            // 关闭资源
            os.close();
            is.close();
        } else {
            resp.getWriter().write("文件不存在，请重试!");
            resp.getWriter().close();
        }
    }
}
